local Industry = require "industry._base"
local _pigsty = {}

---@class pigstyMeta
---@field level integer 等级
---@field next integer 下一生猪时间
---@field retain integer 当前猪的数量

---@class Pigsty : Industry
---@field dead_pigs Creature[] 死猪
---@field lived_pigs Creature[] 活猪
---@field max_retain integer 最大留存数量
---@field current_time integer 当前秒数
---@field is_generate boolean 是否生成
---@field max_generate_time integer 最大生成时间
---@field display_info Unit 信息展示板
---@field levelup_unit Unit 升级单元
---@field metadata pigstyMeta
---@field order integer 编号
---@field pigsGeneration integer 猪群生成器
---@field rootdata storeMeta 根数据
_pigsty.Pigsty = {}
_pigsty.Pigsty.__index = _pigsty.Pigsty
setmetatable(_pigsty.Pigsty, { __index = Industry })

---构造猪圈实例
---@param _role Role 猪圈管理员
---@return Pigsty
function _pigsty.Pigsty:new(_role)
    local parent = Industry:new(_role)
    local instance = setmetatable(parent, self) --[[@as Pigsty]]
    instance.current_time = 30
    instance.max_generate_time = 30
    instance.max_retain = 3
    instance.dead_pigs = {}
    instance.lived_pigs = {}
    instance:bind(_role.get_kv_by_type(Enums.ValueType.Int, "编号"))
    return instance
end

---产业场景绑定
---@param order integer
function _pigsty.Pigsty:bind(order)
    local pig_group_name = "猪群" .. tostring(order)
    local pig_group = GameAPI.get_unit(GameAPI.get_unit_id_by_name(pig_group_name)).get_children() ---@type Creature[]
    for _, pig in ipairs(pig_group) do
        pig.set_model_visible(false)
        pig.set_infinite_reborn_enabled(true)
        pig.set_auto_reborn_enabled(false)
        pig.set_kv_by_type(Enums.ValueType.Vector3, "原始位置", pig.get_position())
        pig.set_kv_by_type(Enums.ValueType.Role, "主人", self.owner)
        pig.set_position(math.Vector3(1000.0, 1000.0, 1000.0))
        pig.disable_gravity()
        table.insert(self.dead_pigs, pig)

        ---猪死亡事件注册
        LuaAPI.unit_register_trigger_event(pig, { EVENT.SPEC_LIFEENTITY_DIE }, function()
            pig.set_position(math.Vector3(1000.0, 1000.0, 1000.0))
            pig.disable_gravity()
            pig.set_model_visible(false)
            for index, lived_pig in ipairs(self.lived_pigs) do
                if lived_pig == pig then table.remove(self.lived_pigs, index) end
            end
            table.insert(self.dead_pigs, pig)
            if self.pigsGeneration ~= -1 then
                self:start_generate()
            end
        end)
    end
    local pigsty_display_name = "猪圈信息" .. tostring(order)
    local pigsty_display = GameAPI.get_unit(GameAPI.get_unit_id_by_name(pigsty_display_name))
    self.display_info = pigsty_display

    local pigsty_levelup_name = "猪圈升级" .. tostring(order)
    local pigsty_levelup = GameAPI.get_unit(GameAPI.get_unit_id_by_name(pigsty_levelup_name))
    pigsty_levelup.set_kv_by_type(Enums.ValueType.Role, "主人", self.owner)
    self.levelup_unit = pigsty_levelup
end

---开始执行
function _pigsty.Pigsty:start()
    self:update_info()
    self:start_generate()
end

---结束
function _pigsty.Pigsty:stop()
    self:stop_generate()
    self:save_data()
end

---开始生成
function _pigsty.Pigsty:start_generate()
    self.pigsGeneration = LuaAPI.global_register_trigger_event({ EVENT.REPEAT_TIMEOUT, 1 }, function()
        if #self.lived_pigs < self.max_retain then
            self.current_time = self.current_time - 1
            self.metadata.next = self.current_time
            if self.current_time <= 0 then
                self:reborn_pig()
                self.current_time = self.max_generate_time
            end
            if #self.lived_pigs >= self.max_retain then
                self:stop_generate()
            end
        end
    end)
end

---停止生成
function _pigsty.Pigsty:stop_generate()
    if self.pigsGeneration ~= -1 then
        LuaAPI.global_unregister_trigger_event(self.pigsGeneration)
    end
    self.pigsGeneration = -1
end

function _pigsty.Pigsty:reborn_pig()
    local pig = self.dead_pigs[1]
    table.insert(self.lived_pigs, pig)
    table.remove(self.dead_pigs, 1)
    pig.reborn(true)
    pig.set_position(pig.get_kv_by_type(Enums.ValueType.Vector3, "原始位置"))
    pig.set_model_visible(true)
    pig.enable_gravity()
end

function _pigsty.Pigsty:set_metadata(metadata)
    Industry.set_metadata(self, metadata)
    self:set_level(metadata.level)
    self.current_time = metadata.next
    for _ = 1, metadata.retain, 1 do
        self:reborn_pig()
    end
end

function _pigsty.Pigsty:set_rootdata(metadata)
    Industry.set_rootdata(self, metadata)
end

function _pigsty.Pigsty:update_info()
    self.display_info.set_billboard_content((
        [==[
猪圈
%d级]==]):format(self.level))
end

---设置等级
---@param level integer 等级
function _pigsty.Pigsty:set_level(level)
    self.level = level
    if self.level <= 10 then
        self.max_generate_time = 30 - (self.level - 1) * 2
    else
        self.max_retain = 3 + math.tointeger(math.floor((self.level - 10) / 2))
    end
    self:update_info()
end

---升级
function _pigsty.Pigsty:levelup()
    self:set_level(self.level + 1)
end

---保存数据
function _pigsty.Pigsty:save_data()
    self.metadata.level = self.level
    self.metadata.next = self.current_time
    self.metadata.retain = #self.lived_pigs
end

---获取信息
function _pigsty.Pigsty:get_info()
    local assets = self.rootdata.assets
    local levelup_money = self:get_levelup_money()
    if self.level + 1 < 20 then
        return ([==[
%s
%s
%s]==]):format(
            assets >= levelup_money and ("可升级(花费 #cffff00%d #cffffff金币)"):format(levelup_money) or
            ("还差 #cff0000%d #cffffff金币升级"):format(levelup_money - assets),
            "本次升级：" .. self:get_levelup_tip(),
            ("下次生猪时间：#c00ff00%d"):format(self.current_time) ..
            ("#cffffff，猪的数量：%s%d / %d"):format(#self.lived_pigs == self.max_retain and "#cff0000" or "#c00ff00", #self
                .lived_pigs, self.max_retain)
        )
    else
        return ([==[
%s
%s]==]):format(
            "#cffff00已满级",
            ""
        )
    end
end

---获取升级所需金币
function _pigsty.Pigsty:get_levelup_money()
    if self.level <= 10 then
        return 150 * self.level
    else
        return 200 * self.level
    end
end

---升级提示
function _pigsty.Pigsty:get_levelup_tip()
    if (self.level + 1) <= 10 then
        return ("生产猪时间 #c00ff00%d -> %d"):format(self.max_generate_time, 30 - self.level * 2)
    elseif (self.level + 1) % 2 == 0 then
        return ("猪的保留数量 #c00ff00%d -> %d"):format(self.max_retain, 3 + math.tointeger(math.floor((self.level - 10) / 2)))
    else
        return "再升一级提升猪的保留数量"
    end
end

return _pigsty
